/*
 *  Jiki - a small lightweight wiki engine.
 *
 *  Copyright 2008 Peter Halbmayer <phalbmayer@gmail.com
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

package at.pmsa.jiki.core;

import java.io.*;

public class JikiScanner {
	
	private static final char EOF = '\u0080';
	private static final char CR = '\r';
	private static final char LF = '\n';
	
//	private static BufferedReader reader;
	
	private static BufferedReader reader;
	private static BufferedReader in;
//	private static PrintWriter out;

	/** Lookahead character. (= next (unhandled) character in the input stream) */
	private static char ch;
	/** Current line in input stream. */
	private static int line_no;
	/** Current column in input stream. */
	private static int col;
	
	public static void init(String d){
		reader = new BufferedReader(new StringReader(d));
	}
	
	public static char nextCh() {
		try {
			ch = (char) in.read();
			if (ch == CR) 
				// ignored, because LF returns to first position in line
				ch = (char) in.read();
			if (ch == LF) {
				//new line, set col to 0
				col = 0;
				return (char)-1;
			}
			else if (ch == (char) -1) {
				// end of file
//				ch = EOF;
				return (char)-1;
			}
			else {
				// standard character
				col++;
			}
		}
		catch (IOException ioe) {
			ch = EOF;
			ioe.printStackTrace();
			return ch;
		}
		return ch;
	}
	
	public static String nextLine(){
		String line;
		try{
			line = reader.readLine();
			if(line != null)
				in = new BufferedReader(new StringReader(line));
		}
		catch(IOException e){
			e.printStackTrace();
			line = null;
		}
		line_no++;
		return line;
	}
}
